from rest_framework import status, viewsets, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.request import Request  # 添加这个导入
from user.models import SysUser  # 使用项目的真实用户模型
from django.db import models
from django.db.models import Q, Max, Count
from django.shortcuts import get_object_or_404
from .models import UserChatRoom, UserChatMessage
from .serializers import (
    UserChatRoomSerializer, 
    UserChatRoomListSerializer,
    UserChatMessageSerializer, 
    UserSimpleSerializer
)
from .user_session import user_session_manager
import logging

logger = logging.getLogger(__name__)


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """用户视图集 - 用于搜索联系人"""
    queryset = SysUser.objects.filter(status=0)  # 只显示正常用户（status=0）
    serializer_class = UserSimpleSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'email']
    
    @action(detail=False, methods=['get'])
    def current_user(self, request):
        """获取当前登录用户信息"""
        # 获取当前登录用户（支持多种识别方式）
        current_user = None
        
        # 方法1: 从请求参数获取current_user_id
        current_user_id = request.query_params.get('current_user_id')
        if current_user_id:
            try:
                current_user = SysUser.objects.get(id=current_user_id, status=0)
                logger.info(f"通过请求参数获取用户: {current_user.username}")
            except SysUser.DoesNotExist:
                logger.warning(f"请求参数中的用户ID {current_user_id} 不存在")
        
        # 方法2: 使用用户会话管理器（fallback）
        if not current_user:
            current_user = user_session_manager.get_current_user_from_request(request)
        
        if not current_user:
            return Response({'error': '未登录或用户信息无效'}, status=status.HTTP_401_UNAUTHORIZED)
        
        user_info = user_session_manager.get_user_display_info(current_user)
        return Response(user_info)
    
    @action(detail=False, methods=['get'])
    def search_contacts(self, request):
        """搜索联系人"""
        query = request.query_params.get('q', '')
        
        # 获取当前登录用户（支持多种识别方式）
        current_user = None
        current_user_id = None
        
        # 方法1: 从请求参数获取current_user_id
        current_user_id_param = request.query_params.get('current_user_id')
        if current_user_id_param:
            try:
                current_user = SysUser.objects.get(id=current_user_id_param, status=0)
                current_user_id = current_user.id
                logger.info(f"通过请求参数获取用户: {current_user.username}")
            except SysUser.DoesNotExist:
                logger.warning(f"请求参数中的用户ID {current_user_id_param} 不存在")
        
        # 方法2: 使用用户会话管理器（fallback）
        if not current_user:
            current_user = user_session_manager.get_current_user_from_request(request)
            if current_user:
                current_user_id = current_user.id
                logger.info(f"通过会话管理器获取用户: {current_user.username}")
        
        # 如果没有当前用户，使用默认值（兼容旧版本）
        if not current_user_id:
            current_user_id = 1
            logger.warning(f"未能获取当前登录用户，使用默认用户ID: {current_user_id}")
        
        if query:
            users = self.queryset.filter(
                Q(username__icontains=query) |
                Q(email__icontains=query)
            ).exclude(id=current_user_id)[:10]
        else:
            users = self.queryset.exclude(id=current_user_id)[:20]
        
        serializer = self.get_serializer(users, many=True)
        return Response(serializer.data)


class UserChatRoomViewSet(viewsets.ModelViewSet):
    """聊天室视图集"""
    serializer_class = UserChatRoomSerializer
    
    def get_queryset(self):
        """获取当前用户参与的聊天室"""
        # 获取当前登录用户（支持多种识别方式）
        current_user = None
        
        # 确保request是DRF的Request对象
        request = self.request
        if not isinstance(request, Request):
            # 如果不是DRF Request对象，创建一个
            from rest_framework.request import Request as DRFRequest
            from rest_framework.parsers import JSONParser
            request = DRFRequest(
                self.request,
                parsers=[JSONParser()],
                authenticators=[],
                negotiator=None,
                parser_context=None
            )
        
        # 方法1: 从请求参数获取（优先，前端主要使用方式）
        current_user_id = request.query_params.get('current_user_id')
        if current_user_id:
            try:
                current_user = SysUser.objects.get(id=current_user_id, status=0)
                logger.info(f"通过请求参数获取用户: {current_user.username}")
            except SysUser.DoesNotExist:
                logger.warning(f"请求参数中的用户ID {current_user_id} 不存在")
        
        # 方法2: 使用用户会话管理器（fallback）
        if not current_user:
            current_user = user_session_manager.get_current_user_from_request(self.request)
        
        if current_user:
            # 只返回当前用户参与的聊天室
            queryset = UserChatRoom.objects.filter(participants=current_user)
            logger.info(f"用户 {current_user.username} 查询聊天室")
        else:
            # 兼容模式：返回所有聊天室（不推荐）
            queryset = UserChatRoom.objects.all()
            logger.warning("未能获取当前用户，返回所有聊天室")
        
        return queryset.annotate(
            last_message_time=Max('messages__timestamp')
        ).order_by('-last_message_time', '-updated_at')
    
    def get_serializer_class(self):
        """根据动作选择序列化器"""
        if self.action == 'list':
            return UserChatRoomListSerializer
        return UserChatRoomSerializer
    
    def create(self, request, *args, **kwargs):
        """创建聊天室"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 检查是否已存在一对一聊天室
        if serializer.validated_data.get('room_type') == 'private':
            participant_ids = request.data.get('participant_ids', [])
            if len(participant_ids) == 1:
                # 查找是否已存在这两个用户的一对一聊天室
                existing_room = UserChatRoom.objects.filter(
                    room_type='private',
                    participants__in=participant_ids
                ).annotate(
                    participant_count=Count('participants')
                ).filter(participant_count=2).first()
                
                if existing_room:
                    # 返回已存在的聊天室
                    room_serializer = UserChatRoomSerializer(existing_room, context={'request': request})
                    return Response(room_serializer.data, status=status.HTTP_200_OK)
        
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    
    @action(detail=True, methods=['get'])
    def messages(self, request, pk=None):
        """获取聊天室消息"""
        room = self.get_object()
        messages = room.messages.all().order_by('timestamp')
        
        # 分页处理
        page = self.paginate_queryset(messages)
        if page is not None:
            serializer = UserChatMessageSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = UserChatMessageSerializer(messages, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['post'])
    def send_message(self, request, pk=None):
        """发送消息到聊天室"""
        room = self.get_object()
        
        # 获取当前登录用户（支持多种识别方式）
        current_user = None
        
        # 方法1: 从请求数据中获取sender_id（前端主要使用方式）
        sender_id = request.data.get('sender_id')
        if sender_id:
            try:
                current_user = SysUser.objects.get(id=sender_id, status=0)
                logger.info(f"通过请求数据获取发送者: {current_user.username}")
            except SysUser.DoesNotExist:
                logger.warning(f"请求数据中的发送者ID {sender_id} 不存在")
        
        # 方法2: 从请求参数获取current_user_id
        if not current_user:
            current_user_id = request.query_params.get('current_user_id')
            if current_user_id:
                try:
                    current_user = SysUser.objects.get(id=current_user_id, status=0)
                    logger.info(f"通过请求参数获取用户: {current_user.username}")
                except SysUser.DoesNotExist:
                    logger.warning(f"请求参数中的用户ID {current_user_id} 不存在")
        
        # 方法3: 使用用户会话管理器（fallback）
        if not current_user:
            current_user = user_session_manager.get_current_user_from_request(request)
        
        if not current_user:
            # 兼容模式：使用默认值
            sender_id = request.data.get('sender_id', 1)
            try:
                current_user = SysUser.objects.get(id=sender_id)
                logger.warning(f"未能获取登录用户，使用参数发送者ID: {sender_id}")
            except SysUser.DoesNotExist:
                return Response({'error': '无效的发送者信息'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证用户是否在聊天室中
        if not room.participants.filter(id=current_user.id).exists():
            return Response({'error': '您不在此聊天室中'}, status=status.HTTP_403_FORBIDDEN)
        
        # 准备消息数据
        message_data = request.data.copy()
        message_data['room'] = room.id
        message_data['sender_id'] = current_user.id
        
        serializer = UserChatMessageSerializer(data=message_data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        message = serializer.save()
        
        # 更新聊天室的updated_at时间
        room.save(update_fields=['updated_at'])
        
        logger.info(f"用户 {current_user.username} 在聊天室 {room.id} 发送消息")
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    
    @action(detail=True, methods=['delete'])
    def delete_room(self, request, pk=None):
        """删除聊天室"""
        room = self.get_object()
        
        # 获取当前登录用户（优先从请求参数获取）
        current_user = None
        
        # 方法1: 从请求参数获取
        current_user_id = request.query_params.get('current_user_id')
        if current_user_id:
            try:
                current_user = SysUser.objects.get(id=current_user_id, status=0)
                logger.info(f"通过请求参数获取用户: {current_user.username}")
            except SysUser.DoesNotExist:
                pass
        
        # 方法2: 从请求头获取
        if not current_user:
            user_id_from_header = request.META.get('HTTP_X_USER_ID')
            if user_id_from_header:
                try:
                    current_user = SysUser.objects.get(id=user_id_from_header, status=0)
                    logger.info(f"通过请求头获取用户: {current_user.username}")
                except SysUser.DoesNotExist:
                    pass
        
        # 方法3: 使用用户会话管理器（兼容性）
        if not current_user:
            current_user = user_session_manager.get_current_user_from_request(request)
        
        # 如果仍然没有用户，返回错误
        if not current_user:
            return Response({
                'error': '未能获取当前用户信息，请在请求中添加 current_user_id 参数'
            }, status=status.HTTP_401_UNAUTHORIZED)
        
        # 验证用户是否在聊天室中
        if not room.participants.filter(id=current_user.id).exists():
            return Response({
                'error': f'用户 {current_user.username} 不在此聊天室中，无法删除'
            }, status=status.HTTP_403_FORBIDDEN)
        
        # 删除聊天室及其消息
        room_id = room.id
        room_info = f"聊天室 {room_id}"
        if room.room_type == 'private' and room.participants.count() == 2:
            other_user = room.participants.exclude(id=current_user.id).first()
            if other_user:
                room_info = f"与 {other_user.username} 的聊天"
        
        room.delete()
        
        logger.info(f"用户 {current_user.username} 删除了{room_info}")
        return Response({
            'message': f'{room_info}已成功删除',
            'deleted_room_id': room_id
        }, status=status.HTTP_200_OK)
    
    @action(detail=False, methods=['post'])
    def create_private_chat(self, request):
        other_user_id = request.data.get('other_user_id')
        
        # 获取当前登录用户（支持多种识别方式）
        current_user = None
        
        # 方法1: 从请求数据中获取current_user_id
        current_user_id = request.data.get('current_user_id')
        if current_user_id:
            try:
                current_user = SysUser.objects.get(id=current_user_id, status=0)
                logger.info(f"通过请求数据获取用户: {current_user.username}")
            except SysUser.DoesNotExist:
                logger.warning(f"请求数据中的用户ID {current_user_id} 不存在")
        
        # 方法2: 从请求参数获取current_user_id
        if not current_user:
            current_user_id = request.query_params.get('current_user_id')
            if current_user_id:
                try:
                    current_user = SysUser.objects.get(id=current_user_id, status=0)
                    logger.info(f"通过请求参数获取用户: {current_user.username}")
                except SysUser.DoesNotExist:
                    logger.warning(f"请求参数中的用户ID {current_user_id} 不存在")
        
        # 方法3: 使用用户会话管理器（fallback）
        if not current_user:
            current_user = user_session_manager.get_current_user_from_request(request)
        
        if not current_user:
            # 兼容模式：使用默认值
            current_user_id = request.data.get('current_user_id', 1)
            try:
                current_user = SysUser.objects.get(id=current_user_id)
                logger.warning(f"未能获取登录用户，使用参数用户ID: {current_user_id}")
            except SysUser.DoesNotExist:
                return Response({'error': '无效的用户信息'}, status=status.HTTP_400_BAD_REQUEST)
        
        if not other_user_id:
            return Response({'error': '需要指定对话用户ID'}, status=status.HTTP_400_BAD_REQUEST)
        
        if current_user.id == other_user_id:
            return Response({'error': '不能与自己创建聊天'}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            other_user = SysUser.objects.get(id=other_user_id)
        except SysUser.DoesNotExist:
            return Response({'error': '目标用户不存在'}, status=status.HTTP_404_NOT_FOUND)
        
        # 查找是否已存在聊天室
        existing_room = UserChatRoom.objects.filter(
            room_type='private'
        ).filter(
            participants=other_user
        ).filter(
            participants=current_user
        ).annotate(
            participant_count=Count('participants')
        ).filter(participant_count=2).first()
        
        if existing_room:
            serializer = UserChatRoomSerializer(existing_room, context={'request': request})
            logger.info(f"用户 {current_user.username} 与 {other_user.username} 的聊天室已存在")
            return Response(serializer.data, status=status.HTTP_200_OK)
        
        # 创建新的聊天室
        room_data = {
            'room_type': 'private',
            'participant_ids': [other_user_id, current_user.id]
        }
        
        serializer = UserChatRoomSerializer(data=room_data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        room = serializer.save()
        
        logger.info(f"用户 {current_user.username} 与 {other_user.username} 创建新聊天室 {room.id}")
        return Response(serializer.data, status=status.HTTP_201_CREATED)


class UserChatMessageViewSet(viewsets.ModelViewSet):
    """聊天消息视图集"""
    serializer_class = UserChatMessageSerializer
    
    def get_queryset(self):
        """获取消息列表"""
        # 获取当前登录用户（支持多种识别方式）
        current_user = None
        
        # 确保request是DRF的Request对象
        request = self.request
        if not isinstance(request, Request):
            # 如果不是DRF Request对象，创建一个
            from rest_framework.request import Request as DRFRequest
            from rest_framework.parsers import JSONParser
            request = DRFRequest(
                self.request,
                parsers=[JSONParser()],
                authenticators=[],
                negotiator=None,
                parser_context=None
            )
        
        # 方法1: 从请求参数获取current_user_id
        current_user_id = request.query_params.get('current_user_id')
        if current_user_id:
            try:
                current_user = SysUser.objects.get(id=current_user_id, status=0)
                logger.info(f"通过请求参数获取用户: {current_user.username}")
            except SysUser.DoesNotExist:
                logger.warning(f"请求参数中的用户ID {current_user_id} 不存在")
        
        # 方法2: 使用用户会话管理器（fallback）
        if not current_user:
            current_user = user_session_manager.get_current_user_from_request(self.request)
        
        room_id = request.query_params.get('room_id')
        if room_id:
            queryset = UserChatMessage.objects.filter(room_id=room_id).order_by('timestamp')
        else:
            queryset = UserChatMessage.objects.all().order_by('-timestamp')
        
        # 如果有当前用户，只返回该用户参与的聊天室的消息
        if current_user:
            queryset = queryset.filter(room__participants=current_user)
            logger.info(f"用户 {current_user.username} 查询消息")
        else:
            # 兼容模式：返回所有消息（不推荐）
            logger.warning("未能获取当前用户，返回所有消息")
        
        return queryset
    
    def create(self, request, *args, **kwargs):
        """创建新消息"""
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        message = serializer.save()
        
        # 更新聊天室的updated_at时间
        message.room.save(update_fields=['updated_at'])
        
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
